package com.evaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.CommunityCollege;
import com.evaluation.service.CommunityCollegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 社区学院对应表管理控制器
 */
@RestController
@RequestMapping("/api/admin/community")
public class AdminCommunityController {

    @Autowired
    private CommunityCollegeService communityCollegeService;

    /**
     * 分页查询社区学院对应列表
     */
    @GetMapping("/list")
    public Result<Page<CommunityCollege>> getCommunityList(@RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(defaultValue = "10") Integer size,
                                   @RequestParam(required = false) String sqmc,
                                   @RequestParam(required = false) String bmmc) {
        try {
            QueryWrapper<CommunityCollege> queryWrapper = new QueryWrapper<>();

            if (sqmc != null && !sqmc.trim().isEmpty()) {
                queryWrapper.like("SQMC", sqmc);
            }

            if (bmmc != null && !bmmc.trim().isEmpty()) {
                queryWrapper.like("BMMC", bmmc);
            }

            queryWrapper.orderByAsc("SQBH", "BMBH");

            Page<CommunityCollege> pageResult = communityCollegeService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询社区学院对应列表失败");
        }
    }

    /**
     * 获取所有社区学院对应关系（用于下拉选择）
     */
    @GetMapping("/options")
    public Result<List<CommunityCollege>> getCommunityOptions() {
        try {
            List<CommunityCollege> communityList = communityCollegeService.list();
            return Result.success(communityList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取社区学院对应选项失败");
        }
    }

    /**
     * 根据社区编号和部门编号查询详情
     */
    @GetMapping("/{sqbh}/{bmbh}")
    public Result<CommunityCollege> getCommunityDetail(@PathVariable String sqbh, @PathVariable String bmbh) {
        try {
            QueryWrapper<CommunityCollege> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SQBH", sqbh);
            queryWrapper.eq("BMBH", bmbh);

            CommunityCollege community = communityCollegeService.getOne(queryWrapper);
            if (community == null) {
                return Result.error("社区学院对应关系不存在");
            }
            return Result.success(community);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询社区学院对应详情失败");
        }
    }

    /**
     * 新增社区学院对应关系
     */
    @PostMapping
    public Result<String> addCommunity(@RequestBody CommunityCollege community) {
        try {
            // 检查是否已存在相同的关系
            QueryWrapper<CommunityCollege> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SQBH", community.getSqbh());
            queryWrapper.eq("BMBH", community.getBmbh());

            CommunityCollege existingCommunity = communityCollegeService.getOne(queryWrapper);
            if (existingCommunity != null) {
                return Result.error("该社区与部门的对应关系已存在");
            }

            boolean result = communityCollegeService.save(community);
            if (result) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加社区学院对应关系失败");
        }
    }

    /**
     * 更新社区学院对应关系
     */
    @PutMapping("/{sqbh}/{bmbh}")
    public Result<String> updateCommunity(@PathVariable String sqbh,
                                  @PathVariable String bmbh,
                                  @RequestBody CommunityCollege community) {
        try {
            // 设置联合主键
            community.setSqbh(sqbh);
            community.setBmbh(bmbh);

            // 使用条件更新，因为是联合主键
            QueryWrapper<CommunityCollege> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SQBH", sqbh);
            queryWrapper.eq("BMBH", bmbh);

            boolean result = communityCollegeService.update(community, queryWrapper);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新社区学院对应关系失败");
        }
    }

    /**
     * 删除社区学院对应关系
     */
    @DeleteMapping("/{sqbh}/{bmbh}")
    public Result<String> deleteCommunity(@PathVariable String sqbh, @PathVariable String bmbh) {
        try {
            // 使用联合主键删除
            QueryWrapper<CommunityCollege> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SQBH", sqbh);
            queryWrapper.eq("BMBH", bmbh);

            boolean result = communityCollegeService.remove(queryWrapper);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除社区学院对应关系失败");
        }
    }

    /**
     * 批量导入社区学院对应关系
     */
    @PostMapping("/import")
    public Result<String> importCommunities(@RequestBody List<CommunityCollege> communityList) {
        try {
            int successCount = 0;
            int errorCount = 0;

            for (CommunityCollege community : communityList) {
                try {
                    // 检查是否已存在相同的关系
                    QueryWrapper<CommunityCollege> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("SQBH", community.getSqbh());
                    queryWrapper.eq("BMBH", community.getBmbh());

                    CommunityCollege existingCommunity = communityCollegeService.getOne(queryWrapper);
                    if (existingCommunity == null) {
                        communityCollegeService.save(community);
                        successCount++;
                    } else {
                        // 更新现有关系
                        communityCollegeService.update(community, queryWrapper);
                        successCount++;
                    }
                } catch (Exception e) {
                    errorCount++;
                }
            }

            return Result.success("导入完成，成功：" + successCount + "条，失败：" + errorCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入社区学院对应关系失败");
        }
    }
} 